package logic

import (
	"context"
	"errors"
	"login-mgr/models/cache"
	"login-mgr/models/mysql"
	"login-mgr/pkg"

	"login-mgr/loginrpc/internal/svc"
	"login-mgr/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserByPhone(mysql.DB, in.Phone); err != nil {
		user = mysql.User{
			Phone:    in.Phone,
			Password: pkg.Md5(in.Password),
		}
		if err := user.UserAdd(mysql.DB); err != nil {
			return nil, errors.New("注册失败")
		}
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码错误")
	}
	result, _ := cache.Rdb.Get(l.ctx, "captcha"+user.Phone).Result()
	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}
	result2, _ := cache.Rdb.Get(l.ctx, "sendSms"+user.Phone).Result()
	if result2 != in.SendSmsCode {
		return nil, errors.New("短信验证码错误")
	}

	return &loginrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
